
    /**  
    * @Title: TableAuthorityAop.java
    * @Package com.frames.table.single.module
    * @Description: 
    * @author likai
    * @date 2019年1月14日
    * @version V1.0  
    */
    
package com.frames.table.single.module;

import java.lang.reflect.Method;

import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import com.utils.mybatis.SqlHelperUtil;
import com.utils.mybatis.SqlUtil;

/**
    * @ClassName: TableAuthorityAop
    * @Description: 表所属微服务范围验证，只有在该微服务业务范围内的表才允许使用
    * @author likai
    * @date 2019年1月14日
    *
    */
@Aspect
@Order(-1)
@Configuration
@ConditionalOnProperty(prefix = "server.table.authority", name = "prefix", matchIfMissing = false)
@ConfigurationProperties(prefix = "server.table.authority")
public class TableAuthorityAop {
	
	public static Logger log = LoggerFactory.getLogger(TableAuthorityAop.class);
	@Autowired
	private SqlSessionFactory sqlSessionFactory;
	
	private String prefix;

	public TableAuthorityAop() {
		super();
		log.info("-------------------------实例化TableAuthorityAop-------------------------");
	}
	@Pointcut("execution(* com.frames.table.single.module.TablesModule.*(..))") 
	public void authorityCheck() {
				
	}	

	@Around("authorityCheck()")	
	public Object checkAround(ProceedingJoinPoint joinPoint) throws Throwable  {		
		if (sqlSessionFactory==null) {
			throw new Exception("---------sqlSessionFactory不能为空！---------");
		}
		Signature s = joinPoint.getSignature();
		
		MethodSignature ms = (MethodSignature)s;
		Method m = ms.getMethod();
		String methodName=m.getName();
		if (methodName.equals("getList")||methodName.equals("getPageList")||methodName.equals("getPageListMap")) {
			methodName="selectList";
		}else if (methodName.equals("getOne")) {
			methodName="slelectOne";
		}
		
		String sql=SqlHelperUtil.getMapperSql(sqlSessionFactory, TablesModule.class,methodName,joinPoint.getArgs());
		String table=SqlUtil.getSqlTableName(sql);
		if (!table.startsWith(prefix)) {
			throw new Exception(table+"不能在该项目中操作，为了严格服务分离，请在正确的项目中操作该表！----sql:"+sql);
		}
		return joinPoint.proceed();
	}
	
	
	public String getPrefix() {
		return prefix;
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	
	
	
}
